<template>
    <div style="width:90%;margin:10px auto 0">
        <!-- pdf -->
        <!-- <iframe :src="pdfUrl" width="100%" height="775px" v-if="pdfShow"></iframe>  -->
        <!-- <shukeOfd v-if="pdfShow" :infoItem="infoItem"></shukeOfd> -->
        <!--1.pdf 2.ofd 3.word 4.xls 5.mp4 6.mp3  7.jpg png  -->
        <div style="width:100%;margin:0 auto" v-if="item.DOC_FILE_TYPE == 'PDF'">
            <pdfDemo :url="pdfUrl"></pdfDemo>
        </div>
        <!-- txt -->
        <iframe :src="txtUrl" width="100%" height="775px" v-if="item.DOC_FILE_TYPE == 'TXT'"></iframe>

        <!-- ofd-->
        <shukeOfd v-if="item.isTypeShow" :infoItem="infoItem"></shukeOfd>
        <!-- word -->
        <div class="conterScroll scroll" v-if="item.DOC_FILE_TYPE == 'DOC' || item.DOC_FILE_TYPE == 'DOCX'">
            <div ref="file"></div>
        </div>
        <!-- xls -->
        <el-tabs v-model="activeName" v-if="item.DOC_FILE_TYPE == 'XLS' || item.DOC_FILE_TYPE == 'XLSX'" type="border-card">
            <el-tab-pane v-for="(item, index) in excelSheet" :key="index" :label="item.name" :name="item.name">
                <div class="table-html-wrap conterScroll scroll" v-html="item.innerHTML"></div>
            </el-tab-pane>
        </el-tabs>

        <!-- mp4 -->
        <div v-if="item.isTypeShow" style="width:620px;margin:16% auto 0">
            <video width="620" height="390" controls muted>
                <source :src="mp4Url" type="video/mp4">
                <source src="movie.ogg" type="video/ogg">
            </video>
        </div>

        <!-- mp3 -->
        <div v-if="item.isTypeShow" style="width:300px;margin:30% auto 0">
            <audio controls>
                <source :src="mp3Url" type="audio/ogg">
                <source :src="mp3Url" type="audio/mpeg">

            </audio>
        </div>
        <!-- jpg  png -->
        <div v-if='item.DOC_FILE_TYPE == "png" || item.DOC_FILE_TYPE == "jpg" || item.DOC_FILE_TYPE == "jpeg"'>
            <!-- <img :src="imgUrl" /> -->
            <previewPicture v-if="imgUrl" :imgUrl="imgUrl"></previewPicture>
        </div>
    </div>
</template>
<script>
import { viewLiu } from "@/api/archive/fileCollection/offlinReception.js";
import pdfDemo from '@/components/componentsPdf/index.vue'
// 引入docx-preview插件
import { renderAsync } from "docx-preview";
//引入xlsx插件
import * as XLSX from 'xlsx';
import '@/assets/styles/file.css'//xlsx样式
import axios from "axios";
import { getToken } from "@/utils/auth";
export default {
    components: { pdfDemo },
    props: ["item", "celldbData"],
    watch: {
        item: {
            handler(valNew) {
                this.getfileTap(valNew)
            },
            immediate: true
        }
    },
    data() {
        return {
            pdfUrl: "",
            txtUrl: "",
            imgUrl:"",
            excelSheet: [],
            activeName: "",
            // 当前分页
            currentPage: 1,
            // 每页显示数量
            pageSize: 10,
            // 数据总数
            total: 0,
        }
    },
    methods: {

        // 预览excel文件
        tableToHtml(workbook) {
            this.excelSheet = [];
            const sheetList = workbook.SheetNames.filter(
                (v) => v.indexOf("数据源") === -1
            );
            this.activeName = sheetList[0];
            sheetList.forEach((sheet) => {
                const worksheet = workbook.Sheets[sheet];
                if (worksheet) {
                    const innerHTML = XLSX.utils.sheet_to_html(worksheet);
                    this.excelSheet.push({
                        name: sheet,
                        innerHTML: innerHTML,
                    });
                } else {
                    this.excelSheet.push({
                        name: sheet,
                        innerHTML: "暂无数据",
                    });
                }
            });
        },
        readWorkbookFromRemoteFile(file) {
            const that = this;
            // 拿取文件对象
            let f = file;
            //这里已经拿到了excel的file文件，若是项目需求，可直接$emit丢出文件
            // that.$emit('getMyExcelData',f);
            // 用FileReader来读取
            let reader = new FileReader();
            // 重写FileReader上的readAsBinaryString方法
            // FileReader.prototype.readAsBinaryString = function(f) {
            //   let binary = "";
            //   let wb; // 读取完成的数据
            //   let outdata; // 你需要的数据
            //   let reader = new FileReader();
            reader.onload = function (e) {
                // 读取成Uint8Array，再转换为Unicode编码（Unicode占两个字节）
                // let bytes = new Uint8Array(reader.result);
                // let length = bytes.byteLength;
                // for (let i = 0; i < length; i++) {
                //   binary += String.fromCharCode(bytes[i]);
                // }
                var data = e.target.result;
                // 接下来就是xlsx
                var wb = XLSX.read(data, {
                    type: "buffer",
                });

                console.log(wb);
                that.tableToHtml(wb);
                var outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
                // 导出格式为json，{表数据：[]}
                that.excelData = outdata;
                that.tableData = outdata.slice(0, 10);
                that.total = outdata.length;
                // 获取数据的key
                var importDataThead = Array.from(Object.keys(outdata[0])).map(
                    (item) => {
                        return item;
                    }
                );
                that.columnHeader = importDataThead;
                that.checkboxTableColumn = importDataThead.slice(0, 9);
            };
            reader.readAsArrayBuffer(f);
        },
        //显示不同文件的方法

        getfileTap(item) {
            if (item.DOC_FILE_TYPE == "DOCX" || item.DOC_FILE_TYPE == "DOC") {
                axios({
                    method: 'POST',
                    url: process.env.VUE_APP_BASE_API + `/archive/detail/view`,
                    params: {
                        docId: item.DOC_ID,
                        categoryId: item.categoryId
                    },
                    headers: {
                        Authorization: "Bearer " + getToken()
                    },
                    responseType: 'arraybuffer' // 更改responseType类型为 arraybuffer
                }).then(res => {

                    this.$nextTick(() => {
                        renderAsync(res.data, this.$refs.file).then(x => console.log(
                            "docx: finished", x))
                    })

                }).catch(err => {
                    console.log(err)
                })
            } else if (item.DOC_FILE_TYPE == "PDF") {
                axios({
                    method: 'POST',
                    url: process.env.VUE_APP_BASE_API + `/archive/detail/view`,
                    params: {
                        docId: item.DOC_ID,
                        categoryId: item.categoryId
                    },
                    headers: {
                        Authorization: "Bearer " + getToken()
                    },
                    responseType: 'blob' // 更改responseType类型为 blob
                }).then(res => {
                    const blob = new Blob([res.data], { type: 'application/pdf;charset-UTF-8' });
                    this.pdfUrl = URL.createObjectURL(blob)

                }).catch(err => {
                    console.log(err)
                })

            } else if (item.DOC_FILE_TYPE == "TXT") {
                axios({
                    method: 'POST',
                    url: process.env.VUE_APP_BASE_API + `/archive/detail/view`,
                    params: {
                        docId: item.DOC_ID,
                        categoryId: item.categoryId
                    },
                    headers: {
                        Authorization: "Bearer " + getToken()
                    },
                    responseType: 'blob' // 更改responseType类型为 blob
                }).then(res => {
                    const blob = new window.Blob([res.data], {
                        type: "text/plain",
                    })
                    this.txtUrl = URL.createObjectURL(blob)

                }).catch(err => {
                    console.log(err)
                })
            } else if (item.DOC_FILE_TYPE == "XLSX" || item.DOC_FILE_TYPE == "XLS") {
                axios({
                    method: 'POST',
                    url: process.env.VUE_APP_BASE_API + `/archive/detail/view`,
                    params: {
                        docId: item.DOC_ID,
                        categoryId: item.categoryId
                    },
                    headers: {
                        Authorization: "Bearer " + getToken()
                    },
                    responseType: 'blob' // 更改responseType类型为 blob
                }).then(res => {
                    let file = new File([res.data], 'demo.ofd')
                    this.readWorkbookFromRemoteFile(file)

                }).catch(err => {
                    console.log(err)
                })
            } else if (item.DOC_FILE_TYPE == "png" || item.DOC_FILE_TYPE == "jpg" || item.DOC_FILE_TYPE == "jpeg") {
                axios({
                    method: 'POST',
                    url: process.env.VUE_APP_BASE_API + `/archive/detail/view`,
                    params: {
                        docId: item.DOC_ID,
                        categoryId: item.categoryId
                    },
                    headers: {
                        Authorization: "Bearer " + getToken()
                    },
                    responseType: 'blob' // 更改responseType类型为 blob
                }).then(res => {
                    const blob = new Blob([res.data], {
                        type: "image/jpeg",
                    })
                    this.imgUrl = window.URL.createObjectURL(blob)
                }).catch(err => {
                    console.log(err)
                })
            }

        }
    }
}
</script>

<style lang="less" scoped>
// ofd  显示样式
#divId>div {
    margin: 0 auto;
}


// xls  样式
.table-html-wrap /deep/ table {

    border-collapse: collapse;

}

/deep/.table-html-wrap table {
    border-collapse: collapse;
    vertical-align: top;
    border-style: none;
    width: 100%;
}

.table-html-wrap /deep/ table td {
    border: 1px solid #ccc;
    min-width: 50px;
    height: 20px;
}

.table-html-wrap /deep/ table th {
    border: 1px solid #ccc;
    min-width: 50px;
    height: 20px;
}
</style>